package com.nopay.dxdwphone.ui.ativity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.azhon.basic.eventbus.MessageEvent;
import com.azhon.basic.utils.ActivityManagerUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.nopay.dxdwphone.base.BaseActivity;
import com.nopay.dxdwphone.bean.CommonResponse;
import com.nopay.dxdwphone.bean.request.UpdateUserInfoRequest;
import com.nopay.dxdwphone.custom_view.BottomPopupWindow;
import com.nopay.dxdwphone.dialog.DialogDownload;
import com.nopay.dxdwphone.dialog.DialogHasNewVersion;
import com.nopay.dxdwphone.dialog.DialogLoginOff;
import com.nopay.dxdwphone.utils.RememberUitls;
import com.nopay.dxdwphone.utils.UpdateUtil;
import com.sl.utakephoto.compress.CompressConfig;
import com.sl.utakephoto.crop.CropOptions;
import com.sl.utakephoto.exception.TakeException;
import com.sl.utakephoto.manager.ITakePhotoResult;
import com.sl.utakephoto.manager.UTakePhoto;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.R;
import com.nopay.dxdwphone.databinding.ActivityAccountInfoBinding;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * @ProjectName: myVisualPhone
 * @Package: cn.cn.myvisualphone.ui.ativity
 * @ClassName: ForgetActivity
 * @Description: java类作用描述
 * @Author: anqi
 * @CreateDate: 2021/5/23 8:05
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/5/23 8:05
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class AcountInfoActivity extends BaseActivity<ActivityAccountInfoBinding> {
    private ArrayList<String> typeList = new ArrayList<>();

    private static final int UPDATE_USER_NAME_REQUEST_CODE = 910;
    private static final int UPDATE_COMPANY_NAME_REQUEST_CODE = 920;
    private static final int UPDATE_COMPANY_POSITION_REQUEST_CODE = 930;

    private String versionName = "";

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {
        binding.rlRoot.setPadding(0, getStatusBarHeight(AcountInfoActivity.this), 0, 0);
        binding.ivBack.setOnClickListener(v -> mSwipeBackHelper.backward());

        String headUrl = SPUtils.getInstance().getString(Constants.SP_HEAD_URL, "");
        headUrl = headUrl.replace("127.0.0.1","125.77.165.58");
        Glide.with(AcountInfoActivity.this).load(headUrl).error(R.mipmap.icon_default_user)
                .placeholder(R.mipmap.icon_default_user).fallback(R.mipmap.icon_default_user).into(binding.ivHead);

        String nickName = SPUtils.getInstance().getString(Constants.SP_USER_NAME, "");
        String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "");
        String companyName = SPUtils.getInstance().getString(Constants.SP_COMPANY_NAME, "");
        binding.tvNickNameText.setText(nickName);
        binding.tvAccountText.setText(phone);
        binding.tvCompanyNameText.setText(companyName);

        // 退出登录
        binding.rlLogout.setOnClickListener(v -> {
            // TODO 登出
            Long userId = SPUtils.getInstance().getLong(Constants.SP_USER_ID, -1);
            api.doLoginOut(userId).enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.body() != null) {
                        if (Constants.RESULT_OK.equals(response.body().getCode())) {
                            RememberUitls.setRemember("", "");
                            SPUtils.getInstance().put(Constants.SP_IS_REMEMBER, false);
                            SPUtils.getInstance().put(Constants.SP_USER_ID, -1L);
                            SPUtils.getInstance().put(Constants.SP_USER_NAME, "");
                            SPUtils.getInstance().put(Constants.SP_PHONE, "");
                            SPUtils.getInstance().put(Constants.SP_HEAD_URL, "");
                            SPUtils.getInstance().put(Constants.SP_COMPANY_NAME, "");
                            SPUtils.getInstance().put(Constants.SP_VIP_STATUS, 0);
                            SPUtils.getInstance().put(Constants.SP_VIP_INVALID_TIME, "");
                            ActivityManagerUtils.getInstance().exitOtherActivity();
                            mSwipeBackHelper.forwardAndFinish(LoginActivity.class);
                            mSwipeBackHelper.executeBackwardAnim();
                        } else {
                            ToastUtils.showShort(response.body().getMsg());
                        }
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    ToastUtils.showShort(AcountInfoActivity.this.getResources().getString(R.string.call_api_error));
                }
            });
        });

        // 昵称修改
        binding.rlNickName.setOnClickListener(v -> mSwipeBackHelper.forward(NickNameActivity.class, UPDATE_USER_NAME_REQUEST_CODE));

        // 公司名称修改
        binding.rlCompany.setOnClickListener(v -> mSwipeBackHelper.forward(CompanyNameActivity.class, UPDATE_COMPANY_NAME_REQUEST_CODE));

        // 职务修改
        binding.rlCompanyPosition.setOnClickListener(v -> {
            // 暂无职务字段
//                mSwipeBackHelper.forward(CompanyPositionActivity.class);
        });

        // 头像修改
        binding.rlHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> list = new ArrayList<>();
                list.add("拍照");
                list.add("相册");
                BottomPopupWindow window = new BottomPopupWindow(AcountInfoActivity.this) {
                    @Override
                    public void onItemChooseFunction(int position, String s) {
                        super.onItemChooseFunction(position, s);
                        if (position == 0){
                            doTakePic();
                        }else{
                            doSelectAlbum();
                        }
                    }

                    @Override
                    public void onCancel() {
                        super.onCancel();
                    }
                };
                window.showDialog(list);
            }
        });

        // 账号注销
        binding.rlLoginOff.setOnClickListener(v ->
                new DialogLoginOff(AcountInfoActivity.this).setOnLoginOffConfirmListener(() -> {
                    Long userId = SPUtils.getInstance().getLong(Constants.SP_USER_ID, -1);
                    api.doLogout(userId + "").enqueue(new Callback<CommonResponse>() {
                        @Override
                        public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                            if (response.body() != null) {
                                if (Constants.RESULT_OK.equals(response.body().getCode())) {
                                    SPUtils.getInstance().clear(true);
                                    RememberUitls.setRemember("", "");
                                    ActivityManagerUtils.getInstance().exitAllActivity();
                                    mSwipeBackHelper.executeBackwardAnim();
                                    mSwipeBackHelper.forwardAndFinish(LoginActivity.class);
                                } else {
                                    ToastUtils.showShort(response.body().getMsg());
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<CommonResponse> call, Throwable t) {
                            ToastUtils.showShort(AcountInfoActivity.this.getResources().getString(R.string.call_api_error));
                        }
                    });
                }).show()
        );

        binding.rlUpdatePassword.setOnClickListener(v -> mSwipeBackHelper.forward(UpdatePasswordActivity.class));

        try {
            versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        binding.tvAppVersion.setText(versionName);
        // 检测版本
        binding.rlAppVersion.setOnClickListener(view -> {
            // TODO 检测版本更新
            api.doGetVersion().enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.body() != null) {
                        if (Constants.RESULT_OK.equals(response.body().getCode())) {
                            String newestVersion = response.body().getData().toString();
                            if(versionName.equals(newestVersion)) {
                                ToastUtils.showShort("已是最新版本");
                            } else {
                                // TODO 提示版本更新
                                new DialogHasNewVersion(AcountInfoActivity.this).setOnUpdateConfirmListener(() -> {
                                    // TODO 确认更新
                                    downloadApk();
                                }).show();
                            }
                        } else {
                            ToastUtils.showShort("已是最新版本");
                        }
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    ToastUtils.showShort(AcountInfoActivity.this.getResources().getString(R.string.call_api_error));
                }
            });
        });

        binding.rlUserAgreement.setOnClickListener(view -> {
            // TODO 用户协议
            mSwipeBackHelper.forward(UserAgreementActivity.class);
        });

        binding.rlPrivacy.setOnClickListener(view -> {
            // TODO 隐私政策
            mSwipeBackHelper.forward(PrivacyActivity.class);
        });
    }

    private void doSelectAlbum() {
        File picFIle = getPicName();
        final CropOptions cropOptions = new CropOptions.Builder()
//                        .setAspectX(1080).setAspectY(1920)
//                .setOutputX(100).setOutputY(1)
                .setWithOwnCrop(true)
                .create();

        UTakePhoto.with(getActivity())
                .openAlbum()
                .setCrop(cropOptions)
                .setCompressConfig(new CompressConfig.Builder().setTargetUri(Uri.fromFile(picFIle)).setLeastCompressSize(50).create())
                .build(new ITakePhotoResult() {
                    @Override
                    public void takeSuccess(@NonNull List<Uri> uriList) {
                        if (uriList.get(0) != null) {
                            try {
                                ParcelFileDescriptor pfd = getActivity().getContentResolver().openFileDescriptor(uriList.get(0), "r");
                                if (pfd != null) {
                                    Bitmap bitmap = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
                                    String path = picFIle.getPath();
                                    File picFile = new File(path);
                                    doCompressPic(picFile);
                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void takeFailure(TakeException ex) {

                    }

                    @Override
                    public void takeCancel() {

                    }
                });
    }

    private void doTakePic() {
        File picFIleCamera = getPicName();
        final CropOptions cropOptions1 = new CropOptions.Builder()
                .setAspectX(1080).setAspectY(1920)
//                .setOutputX(100)
//                .setOutputY(1)
                .setWithOwnCrop(true)
                .create();

        UTakePhoto.with(getActivity())
                .openCamera()
                .setCrop(cropOptions1)
                .setCompressConfig(new CompressConfig.Builder().setTargetUri(Uri.fromFile(picFIleCamera)).setLeastCompressSize(50).create())
                .build(new ITakePhotoResult() {
                    @Override
                    public void takeSuccess(@NonNull List<Uri> uriList) {
                        if (uriList.get(0) != null) {
                            try {
                                ParcelFileDescriptor pfd = getActivity().getContentResolver().openFileDescriptor(uriList.get(0), "r");
                                if (pfd != null) {
                                    Bitmap bitmap = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
//                                    photoIv.setImageToCrop(bitmap);
                                    String path = picFIleCamera.getPath();
                                    File picFile = new File(path);
                                    doCompressPic(picFile);

                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void takeFailure(TakeException ex) {

                    }

                    @Override
                    public void takeCancel() {

                    }
                });
    }

    private void doCompressPic(File picFile) {
        //调用鲁班
        Luban.with(AcountInfoActivity.this)
                .load(picFile)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI

                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        LogUtils.e("anqi",  file.getName());
                        Map<String, RequestBody> bodyMap = new HashMap<>();
                        bodyMap.put("file" + "\";filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
                        api.doUploadAvatar(bodyMap).enqueue(new Callback<CommonResponse>() {
                            @Override
                            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                                if (response.body() != null) {
                                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                                        CommonResponse body = response.body();
                                        SPUtils.getInstance().put(Constants.SP_HEAD_URL, body.getUrl());
                                        ToastUtils.showShort(response.body().getMsg());
                                        String headUrl = SPUtils.getInstance().getString(Constants.SP_HEAD_URL, "");
                                        headUrl = headUrl.replace("127.0.0.1","125.77.165.58");
                                        Glide.with(AcountInfoActivity.this).load(headUrl).error(R.mipmap.default_user)
                                                .placeholder(R.mipmap.default_user).fallback(R.mipmap.default_user).into(binding.ivHead);
                                        EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_CHANGE_HEAD));
//                                        mSwipeBackHelper.backward();

                                        saveHeadUrl();
                                    } else {
                                        ToastUtils.showShort(response.body().getMsg());
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<CommonResponse> call, Throwable t) {
                                ToastUtils.showShort(AcountInfoActivity.this.getResources().getString(R.string.call_api_error));
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();
    }

    @NotNull
    private File getPicName() {
        String dateTime = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date());
        return new File(
                getFilesDir(),
                "VisualPhone/Photo/compress/" + dateTime + ".jpg");
    }

    @NotNull
    private String getPath() {
        return new File(
                getFilesDir(),
                "VisualPhone/Photo/compress/").getPath();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK) {
            if(requestCode == UPDATE_USER_NAME_REQUEST_CODE) binding.tvNickNameText.setText(SPUtils.getInstance().getString(Constants.SP_USER_NAME, ""));

            if(requestCode == UPDATE_COMPANY_NAME_REQUEST_CODE) binding.tvCompanyNameText.setText(SPUtils.getInstance().getString(Constants.SP_COMPANY_NAME, ""));

            if(requestCode == UpdateUtil.REQUEST_INSTALL_UNKNOWN_APP_CODE) UpdateUtil.install(AcountInfoActivity.this);
        }
    }

    private void saveHeadUrl() {
        UpdateUserInfoRequest bean = new UpdateUserInfoRequest();
        bean.setPhone(SPUtils.getInstance().getString(Constants.SP_PHONE, ""));
        bean.setHeadUrl(SPUtils.getInstance().getString(Constants.SP_HEAD_URL, ""));
        bean.setUserName(SPUtils.getInstance().getString(Constants.SP_USER_NAME, ""));
        bean.setCompanyName(SPUtils.getInstance().getString(Constants.SP_COMPANY_NAME, ""));

        RequestBody body = getRequestBody(bean);
        api.doUpdateUserInfo(body).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        ToastUtils.showShort("头像保存成功");
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                ToastUtils.showShort(AcountInfoActivity.this.getResources().getString(R.string.call_api_error));
            }
        });
    }

    private void downloadApk() {
        DialogDownload dialogDownload = new DialogDownload(AcountInfoActivity.this);
        dialogDownload.show();
        UpdateUtil.downloadApk(new UpdateUtil.OnDownloadApkListener() {
            @Override
            public void inProgress(int progress) {
                runOnUiThread(() -> dialogDownload.setProgress(progress));
            }

            @Override
            public void onSuccess(File apkFile) {
                runOnUiThread(() -> {
                    dialogDownload.dismiss();
                    UpdateUtil.install(AcountInfoActivity.this);
                });

            }

            @Override
            public void onError(Throwable e) {
                dialogDownload.dismiss();
                ToastUtils.showShort("下载失败");
            }
        });
    }
}
